package com.xuecheng.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.basic.api.BasicClient;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.config.MinioProperties;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.CoursePub;
import com.xuecheng.content.mappers.CoursePubMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CoursePubService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exceptions.BusinessException;
import freemarker.template.Configuration;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-09-17
 */
@Service
@Slf4j
public class CoursePubServiceImpl extends ServiceImpl<CoursePubMapper, CoursePub> implements CoursePubService {

    @Autowired
    private CourseBaseService courseBaseService;

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private BasicClient basicClient;

    @Autowired
    private Configuration configuration;

    /**
     * 根据课程id，查询预览数据(课程发布对象CoursePub)
     *  1、课程数据
     *  2、课程计划
     *  3、讲师数据
     */
    public Map<String, Object> preview(Long courseBaseId) {
        //1、查询课程数据
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        //2、查询课程计划数据
        ResponseResult<TeachplanVo> treeNodes = teachplanService.treeNodes(courseBaseId);
        TeachplanVo vo = treeNodes.getData();
        //3、查询课程讲师数据(略)
        //4、调用feign接口，根据id查询课程分类的名称
        String stName = this.getCategroyName(courseBase.getSt());
        String mtName = this.getCategroyName(courseBase.getMt());
        //5、构造CoursePub对象
        CoursePub coursePub = BeanHelper.copyProperties(courseBase, CoursePub.class);
        coursePub.setId(null);
        coursePub.setCourseId(courseBase.getId());
        //设置分类
        coursePub.setStName(stName);
        coursePub.setMtName(mtName);
        //设置课程计划
        coursePub.setTeachplan(JSON.toJSONString(vo));
        //设置讲师(略)
        //6、返回Map集合
        Map<String, Object> map = new HashMap<>();
        map.put("coursePub",coursePub);
        map.put("teachplanNode",vo);
        return map;
    }

    /**
     * 获取分类名称
     */
    private String getCategroyName(String id) {
        ResponseResult<CategoryVo> result = basicClient.findById(id);
        CategoryVo data = result.getData();
        return data.getName();
    }

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties properties;

    @Autowired
    private PublishHtmlService publishHtmlService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //课程发布
    public ResponseResult publish(Long courseBaseId) throws Exception {
        //A---保存课程发布数据
        //1、根据课程id查询课程
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        //2、构造课程发布对象
        Map<String, Object> map = this.preview(courseBaseId);
        CoursePub coursePub = (CoursePub) map.get("coursePub"); //最新的数据，缺少id
        //3、根据课程id，查询此课程是否存在发布数据
        LambdaQueryWrapper<CoursePub> qw = new LambdaQueryWrapper<>();
        qw.eq(CoursePub::getCourseId,courseBaseId);
        CoursePub one = this.getOne(qw);
        Boolean flag = false;
        if(one == null) {
            //3.1 如果不存在，保存
            flag = this.save(coursePub);
        }else {
            //3.2 如果存在，更新
            coursePub.setId(one.getId());
            flag = this.updateById(coursePub);
        }
        if(!flag) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        //4、更新课程状态
        courseBase.setAuditStatus(CourseConstants.AUDIT_PUBLISHED_STATUS);
        courseBaseService.updateById(courseBase);

        log.info("发布课程主线程："+Thread.currentThread().getName());

        //B---生成静态页面，上传minio
        try {
            publishHtmlService.publish(map,coursePub.getId());
        }catch (Exception e) {
            log.error(e.getMessage(),e);
        }

        //C---发送MQ消息
        rabbitTemplate.convertAndSend("content-exchange",
                "course.pub",
                coursePub.getId()); //交换机名称，路由key，消息内容

        return ResponseResult.okResult();
    }
}
